﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace FileSystemCustomClasses
{
	public class FileSystemListService
	{
		private static readonly object _listLock = new object();
		private bool _isCompleted;
		private List<FileSystemItem> _itemList;

		public bool IsCompleted
		{
			get
			{
				bool returnVal;
				lock (_listLock)
				{
					returnVal = _isCompleted;
				}

				return returnVal;
			}

			set
			{
				lock (_listLock)
				{
					_isCompleted = value;
				}
			}
		}

		public FileSystemListService()
		{
			_itemList = new List<FileSystemItem>();
		}

		public void Add(FileSystemItem argItem)
		{
			lock (_listLock)
			{
				_itemList.Add(argItem);
				Monitor.Pulse(_listLock);
			}
		}

		public List<FileSystemItem> TakeAll()
		{
			List<FileSystemItem> localList = new List<FileSystemItem>();

			lock (_listLock)
			{
				if (!_isCompleted)
				{
					//We only need to wait if we are not complete
					while (_itemList.Count == 0)
					{
						Monitor.Wait(_listLock);
					}
				}

				localList.AddRange(_itemList);
				_itemList.Clear();
			}

			return localList;
		}
	}

	public class FileListUpdateArgs : EventArgs
	{
		public List<FileSystemItem> ItemList { get; set; }

		public FileListUpdateArgs(List<FileSystemItem> argList)
		{
			ItemList = new List<FileSystemItem>();
			ItemList.AddRange(argList);
		}
	}
}